package com.security;

import com.exceptions.MyAccessDeniedException;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

@Component
@Slf4j
public class DynamicPermission {

    /**
     * 动态权限验证
     * @param request request
     * @param authentication authentication
     * @return boolean
     */
    public boolean checkPermission(HttpServletRequest request, Authentication authentication) {
        log.info(request.getRequestURI());
        Object principal = authentication.getPrincipal();
        if(principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            for(GrantedAuthority grantedAuthority:authorities) {
                if(grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                    return true;
                }
            }
            //得到当前的账号
            String username = userDetails.getUsername();
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            //当前访问路径
            String requestURI = request.getRequestURI();
            //提交类型
            String urlMethod = request.getMethod();
            return false;
        }else{
            throw new MyAccessDeniedException("内存的用户信息不是UserDetails类型！");
        }
    }
}

























